package com.ITD.service.Impl;

import com.ITD.mapper.UserMapper;
import com.ITD.pojo.User;
import com.ITD.service.UserService;
import com.ITD.vo.ErrorCode;
import com.ITD.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUser(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //查询，通过username、password查询
        queryWrapper.eq(User::getUserName,username);
        queryWrapper.eq(User::getPassword,password);
        //动态获得结果，根据你想要的属性获得
        queryWrapper.select(User::getId,User::getUserName);
        //查询一个数据
        queryWrapper.last("limit 1");
        System.out.println(userMapper.selectOne(queryWrapper));
        //bug就在这个部分
        //返回数据
        User user =userMapper.selectOne(queryWrapper);
        //bug就在这个部分
        return user;
    }
    @Override
    public Result changePassword(String userName,String oldPassword, String newPassword) {
        //加密
        String sha1pwd = DigestUtils.sha1Hex(oldPassword);
        if(findUser(userName,sha1pwd)==null)
            return Result.fail(ErrorCode.USER_NO_EXIST.getCode(), ErrorCode.USER_NO_EXIST.getMsg(), "有误");

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
       //加密
        String sha1pwd2 = DigestUtils.sha1Hex(newPassword);
        updateWrapper.eq(User::getUserName,userName)
                .set(User::getPassword,sha1pwd2);
        int update = userMapper.update(null, updateWrapper);
        if(update!=0)
            return Result.success(null);
        else
            return Result.fail(ErrorCode.USER_NO_EXIST.getCode(), ErrorCode.USER_NO_EXIST.getMsg(), "修改密码失败");
    }
}
